package com.xctech.yace.pool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ProduceThreadPool {

    private static TimeUnit timeUnit = TimeUnit.SECONDS;

    private static BlockingQueue queue = new LinkedBlockingQueue<Runnable>();

    private static AtomicInteger index = new AtomicInteger(0);

    private static ThreadPoolExecutor pool = null;

    public static ThreadPoolExecutor getInstance(){
        if(pool == null){
            initPool();
        }
        return pool;
    }

    private static void initPool(){
        int corePoolSize = 50;
        int maximumPoolSize = 100;
        long keepAliveTime = 60;

        pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, queue,
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r,"pool_"+r.hashCode());
                    }
                },new ThreadPoolExecutor.DiscardOldestPolicy());
        System.out.println("线程池 初始化完毕 init ok ...."+index.incrementAndGet());
    }

    public static void stopPool(Long interval){
        try {
            System.out.println(interval/1000+"秒后停止线程池");
            Thread.sleep(interval);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pool.shutdownNow();
        System.out.println(pool);
    }
}
